package org.batatasframework.properties.beans;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.batatasframework.expression.ExpressionClause;
import org.batatasframework.expression.Named;
import org.batatasframework.properties.ProperitesGroup;
import org.batatasframework.properties.PropertiesName;

public class InternalProperitesGroup implements ProperitesGroup{
	private final List<ExpressionClause> items = new ArrayList<>();
	private final PropertiesName name;
	
	public InternalProperitesGroup(PropertiesName name){
		this.name = name;
	}
	
	public List<ExpressionClause> getItems() {
		return items;
	}

	@Override
	public PropertiesName getName() {
		return name;
	}

	@Override
	public Iterator<ExpressionClause> iterator() {
		return items.iterator();
	}

	@Override
	public List<ExpressionClause> cloneOf() {
		return new ArrayList<>(items);
	}

	@Override
	public boolean is(String groupName) {
		return name.equals(groupName);
	}
	
	private boolean mergeable(ExpressionClause parent, ExpressionClause child){
		if(null != child){
			Named childName = child.getName();
			Named parentName = parent.getName();
			return childName.associated(parentName);
		}
		return false;
	}

	@Override
	public List<ExpressionClause> mergeOf() {
		int size = items.size();
		ExpressionClause[] ecs = items.toArray(new ExpressionClause[size]);
		List<ExpressionClause> newItems = new ArrayList<>();
		
		for(int i = 0; i < size; i++){
			ExpressionClause candidateParent = ecs[i];
			if(null != candidateParent){
				
				for(int j = i + 1; j < size; j++){
					ExpressionClause candidateChild = ecs[j];
					if(mergeable(candidateParent,candidateChild)){
						
						candidateParent.addChild(candidateChild);
						ecs[j] = null;
					}
				}
				
				newItems.add(candidateParent);
			}
		}
		return newItems;
	}
}
